package http.secure.common.keys.impl;

import http.secure.common.keys.SecureGuidSession;
import http.secure.common.keys.SecureKeyStore;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public record LocalKeyStore(SecureGuidSession support) implements SecureKeyStore {
    private static final Map<String, String> VALUE_STORE = new ConcurrentHashMap<>();
    private static final Map<String, Long> EXPIRE_TIME_STORE = new ConcurrentHashMap<>();

    @Override
    public void save(String key, String value, long timeout) {
        String guid = support.getGuid(); // 保证非空
        String cacheKey = buildCacheKey(guid, key);
        long expireAt = System.currentTimeMillis() + timeout;
        VALUE_STORE.put(cacheKey, value);
        EXPIRE_TIME_STORE.put(cacheKey, expireAt);
    }

    @Override
    public String get(String key) {
        String guid = support.getGuid();
        String cacheKey = buildCacheKey(guid, key);
        Long expireAt = EXPIRE_TIME_STORE.get(cacheKey);
        if (expireAt == null || System.currentTimeMillis() >= expireAt) {
            delete(key);
            return null;
        }
        return VALUE_STORE.get(cacheKey);
    }

    @Override
    public Long getExpireTime(String key) {
        String guid = support.getGuid();
        String cacheKey = buildCacheKey(guid, key);
        Long expireAt = EXPIRE_TIME_STORE.get(cacheKey);
        if (expireAt == null) {
            return null;
        }
        long now = System.currentTimeMillis();
        if (now >= expireAt) {
            delete(key);
            return null;
        }
        return expireAt - now; // 剩余毫秒数
    }

    @Override
    public void delete(String key) {
        String guid = support.getGuid();
        String cacheKey = buildCacheKey(guid, key);
        VALUE_STORE.remove(cacheKey);
        EXPIRE_TIME_STORE.remove(cacheKey);
    }

    private String buildCacheKey(String guid, String key) {
        return guid + ":" + key;
    }
}